/**
 * Created by Sherry on 2016/12/24.
 */
import Util from '../libs/util';
// import Config from '../config/config'
import Request from '../config/request'
import User from '../module/user'

class Cart{

    constructor(cart=[],cartObj={},idList=[]){

        this.cart=cart;
        this.cartObj=cartObj;
        this.idList=idList;
        console.log(this)
    }

    
    init(query) {
        var queryData =query;

        if(queryData.res == 'clear'){

            localStorage.removeItem('CART');
            delete queryData.res;

            var su = Util.objToQueryString(queryData),
                se = (su == '' ? '' : '?' + su);

            history.replaceState(history.state, null, se);

        }

        var cart = localStorage.getItem('CART');

        if (cart) {

            this.saveCart(JSON.parse(cart));

        }

    }
    add(id, num, title,total=0) {
        console.log(total)
        if(isNaN(num)){
            return false;
        }
        if (this.cartObj[id]) {

            this.cartObj[id].number += Number.parseInt(num);

        } else {

            this.cartObj[id] = {
                id: id,
                number: Number.parseInt(num),
                title: title,
                total: Number.parseInt(total),
            }

        }

        if (this.cartObj[id].number <= 0) {
            delete this.cartObj[id];
        }
        console.log(this.cartObj[id])
        this.objSave();

        return this.cart.length;
    }
    removeItem(id) {
        delete this.cartObj[id];
        this.objSave();
    }
    changeItem(id, num) {
        if(isNaN(num)){
            return false;
        }
        if (!this.cartObj[id]) {
            this.add(id, num);
        } else {
            this.cartObj[id].number = num;
            this.objSave();
        }
    }
    objSave() {
        this.cart = Util.objToArr(this.cartObj);
        this.saveCart();
    }
    saveCart(arr) {

        if (typeof arr == 'object' && (arr instanceof Array)) {
            this.cart = arr;
            this.cartObj = Util.arrToObj(this.cart, 'id');
        }

        this.idList = [];;

        for (var i = 0, len = this.cart.length; i < len; i++) {
            this.idList.push(this.cart[i].id);
        };
        //默认10夺宝币
        var cart = localStorage.getItem('CART');
        if(!cart)
            cart = '[]';
        var cart_json = Util.arrToObj(JSON.parse(cart), 'id');
        for (var i = 0; i < this.cart.length; i++) {
            console.log()
            if(!cart_json[this.cart[i].id] && this.cart[i].total>=50){
                this.cart[i].number = 10;

            }else if(cart_json[this.cart[i].id]=='39266'||this.cart[i].title.indexOf('国庆大促')>0){
                this.cart[i].number = 10;
            }
        }


  
        localStorage.setItem('CART', JSON.stringify(this.cart));
    }
    clear(){
        this.saveCart([]);
    }
    getCartNum(){
        return this.cart.length;
    }
    addCart(btn) {
        var $_btn = $(btn),
            $_wrap = $_btn.closest('[data-gi]'),
            $_img = $_wrap.find('[data-img]'),
            $_imgSrc = $_wrap.find('[data-img] img').attr('src'),
            $_cart = $('[data-fn="cartnum"]'),
            offset = $_img.offset(),
            id = $_wrap.attr('data-gi'),
            title=$_wrap.attr('data-title'),
            isTen=$_wrap.attr('data-ten');
        if ($_cart.length > 0) {
            var div = $('<div class="w-goods-pic cart-anim"></div>'),
                cof = $_cart.offset(),
                top = cof.top + $_cart.height() / 2 - $_img.height() / 2,
                left = cof.left + $_cart.width() / 2 - $_img.width() / 2,
                style = {
                    "background-image": 'url('+$_imgSrc+')',
                    "width": $_img.width(),
                    "height": $_img.height(),
                    "top": top,
                    "left": left,
                    "-webkit-transform": "scale(1) translate3d(" + (offset.left - left) + "px," + (offset.top - top) + "px,0) rotateZ(-720deg)",
                    "transform": "scale(1) translate3d(" + (offset.left - left) + "px," + (offset.top - top) + "px,0) rotateZ(-720deg)",
                    "webkitTransform": "scale(1) translate3d(" + (offset.left - left) + "px," + (offset.top - top) + "px,0) rotateZ(-720deg)"
                };


            div.css(style);

            div.on('webkitAnimationEnd', function(e) {
                div.remove();
            });

            $('body').append(div);

            setTimeout(()=>{
                div.addClass('cart-anim2')
            },10)
            setTimeout(()=>{
                div.remove();
            },2000)



            var num;

            if(isTen=='1') num = this.add(id, 10,title);
            else num = this.add(id, 1,title);

            if (num > 0) {

                $('[data-fn="cartnum"]').html(num).css('visibility','visible');
            } else {
                $('[data-fn="cartnum"]').html(num).css('visibility','hidden');
            }
        }
    }
    formatList(data) {
   
        var arr = data.item,
            selected=data.selected,
            list = [],
            obj = {},
            total = 0,
            goodsNum = 0;



      
        for (var i = 0; i < arr.length; i++) {


            obj = {
                id: arr[i].id,
                number: data.item[i].islimit=='1'?Number.parseInt(arr[i].limit):Math.min(this.cartObj[arr[i].id].number, Number.parseInt(arr[i].limit)),
                total:arr[i].totalNeed,
                title:arr[i].title
            };
            if(!!selected){
                if(selected.length>0&&selected.length==arr.length){
                    obj.number=selected[i];
                }
            }


            arr[i].number = obj.number;
            total+=data.item[i].islimit=='1'?Number.parseInt(arr[i].limit):obj.number;
            goodsNum++;

            list.push(obj);
        };
   
        data.total = total;
        data.goodsNum = goodsNum;
  
        this.saveCart(list);
    }

    async freeBuy(id) {
        
        let res= await Request.post(Config.apiDomain + '/Pay/freePay',{data:{good_id: id,token:User.token}});
        return res;
    }


    async getList(){
        if (this.idList.length == 0) {

            return {
                "status": 200,
                "msg": "",
                "data": {}
            };
        }

        let res = await Request.post(Config.apiDomain + '/Cart/listCart?token='+User.token,{data: {
            idstr: this.idList.join(',')
        }})

        return res;
    }

    async getCoupon(sids,nums){
        
            let res = await Request.post(Config.apiDomain + '/Coupon/getCoupon?token='+User.token,{data: {
                sids: sids.join(','),
                nums: nums.join(',')
            }})
            
            if(res.status=200 && res.data.item.length>0){
                //去除数组重复元素/
                for(let i=0,len=res.data.item.length;i<len;i++){
                    for(let j=i+1;j<len;j++){
                        if(res.data.item[i].id===res.data.item[j].id){
                            res.data.item.splice(j,1);
                            j--;
                            len--;
                        }
                    }
                }
            }else{
                res.data.item=[];
            }
            
            return res;
        
    }
};

let cart=new Cart();

export default cart;